<template>
	<div class="deployClass" style="margin-top:10px;">
		<Row style="margin-bottom:10px;">
			<Select filterable v-model="exp" style="width:150px;margin-right:15px" v-if="classNumberInfo.expList.length > 1" @on-change="getEnvironData">
				<Option v-for="item in classNumberInfo.expList" :value="JSON.stringify(item)" :key="item.expid" :title="item.expName">{{ item.expName }}</Option>
			</Select>
			<Input v-model.trim="user" style="width:180px;margin-right:15px" placeholder="请输入昵称搜索" clearable @on-change="getEnvironData"></Input>
			<div style="float:right;">
				<!--<Tag type="border" color="success">在线人数： {{onlineNum}}</Tag>-->
				<!--<Tag type="border" color="primary">接入人数： {{loginNum}}</Tag>-->
					<Button type="warning" :loading="pauseLoading" size="small" class="ml4" @click="startRecording"
					v-if="!videoStart"
						>屏幕录制</Button>
						<Button type="warning" :loading="pauseLoading" size="small" class="ml4" @click="stopRecording" 
						v-if="!(!videoStart)"
						>结束录制</Button>
				<Poptip confirm title="确认要暂停课节吗？" @on-ok="pauseClassNumber" transfer word-wrap width="200" :disabled="pauseLoading">
					<Button type="warning" :loading="pauseLoading" size="small" class="ml4"
						v-if="!(disbledAllBtn || courseStatus != 2)"
					>暂停</Button>
				</Poptip>
				<Poptip confirm title="确认要恢复课节吗？" @on-ok="resumeClassNumber" transfer word-wrap width="200" :disabled="resumeLoading">
					<Button type="info" :loading="resumeLoading" size="small" class="ml4"
						v-if="!(disbledAllBtn || courseStatus != 4)">恢复</Button>
				</Poptip>
				<Poptip confirm title="确认要结束课节吗？" @on-ok="finishClassNumber" transfer word-wrap width="200" :disabled="finishLoading">
					<Button type="error" :loading="finishLoading" size="small" class="ml4" 
					 v-if="!(disbledAllBtn || [0, 1, 3].includes(courseStatus))">结束</Button>
				</Poptip>
				<Button type="info" size="small" class="ml4"
					v-if="!(disabledBatchDeploy || batchDeployLoading || disbledAllBtn || step != 0)"
					@click="batchDeployClass">批量部署</Button>
				<Poptip confirm title="确认销毁选中的环境吗？" @on-ok="batchExperimentDestroy" transfer word-wrap width="200">
					<Button type="error" size="small" 
					v-if="!(disabledBatchDestroy || batchDestroyLoading || disbledAllBtn || step == 0)"
					class="ml4">批量销毁</Button>
				</Poptip>
				<Poptip confirm title="确定重置选中的环境吗？" @on-ok="batchExperimentRestart" transfer word-wrap width="200" v-if="cloudType !== 'h3c'">
					<Button type="error" size="small"
					 v-if="!(disabledBatchDestroy || batchDestroyLoading || disbledAllBtn || step == 0)"
					 class="ml4">批量重置</Button>
				</Poptip>
			</div>
			<!-- <video controls autoplay playsinline ref="video" width="400" height="300"></video> -->
		</Row>
		<div style="margin-bottom:10px" v-if="selectOpUsers.length > 0">已选择：
			<Tag v-for="user in selectOpUsers" :key="user.userId" color="blue">{{user.userName}}</Tag>
		</div>
		<Table border :columns="environCol" :row-class-name="rowClassName" :data="environList" @on-select="addDeployUser" @on-select-all="addDeployUser" @on-select-cancel="removeDeployUser" @on-select-all-cancel="removeDeployUser"></Table>
		<Page :total="environTotal" :page-size="environPageSize" :current="environPage" 
		show-elevator
		show-total style="text-align:center;margin-top:10px;" @on-change="changeEnvironPage" />
		<!--  虚拟机列表，提供接入虚拟机-->
		<Modal v-model="vmsModal" :mask-closable="false" title="虚拟机列表" width="90">
			<Table border :columns="vmsCol" :data="vmsRow(vmsList)" v-if="vmsModal" :max-height="400"></Table>
		</Modal>
	</div>
</template>

<script>
	import RecordRTC from 'recordrtc'
	import encryption from '@/libs/encryption.js'
	import { mapState } from 'vuex'
	import {
		getCompanyUsersInfo
	} from '@/api/users'
	import {
		deployClass,
		updateClassStatus,
		batchExperimentDestroy,
		queryClassNumberList,
		getClassNumberDetail,
		pauseClassNumber,
		resumeClassNumber,
		finishClassNumber
	} from '@/api/selfStudy/class.js'
	import {
		getRecord
	} from '@/api/selfStudy/access.js'
	import {
		getstatusbyprjid
	} from '@/api/drill'
	import {
		courseDetail,
		expEnv,
		getVms,
		experimentDestroy
	} from '@/api/selfStudy/courseExp.js'
	import {
		queryVmStatus,
		opVms,
		rebuildVm,
		rebootVm
	} from '@/api/remote.js'
	import {
		getmemdata,
		batchOpVm
	} from '@/api/drill_compete'
	import vmsType from './vmsType'
	import {getFilesData,delFile} from '@/api/uploadFile.js'
	import {addRecord} from '@/api/selfStudy/record.js'
	import { getDictInfoByName } from '@/api/dict'
	export default {
		name: 'deployClass',
		components: {
			vmsType
		},
		props:{
			// 因为不能使用classNumberId来触发倒计时结束后，刷新开始的课节列表。所以用一个新的参数来观察
			countDownClassNumberId: {
				type: String,
				default: ''
			},
			classNumberId: {
				type: String,
				default: ''
			},
			classNumberInfo:{
				type:Object,
				required:true,
				validator(value) {
					return value.classNumberId && value.expList
				}
			},
			classInfo:{
				type:Object,
				required:true,
				validator(value) {
					return value.id && value.type && value.status
				}
			},
			step:{
				type:Number,
				default:0
			},
			disbledAllBtn:{
				type:Boolean,
				default:false
			},
		},
		data() {
			let September = sessionStorage.getItem('November')
			September = JSON.parse(encryption.SelfUseDecrypt(September))
			return {
				screenRecording:0,
				recorderForm:{
				},
				videoPath:'',
				upLoadUrl:``,
				 video: null,
				videoStart: false,
				recorder: null,

				pauseLoading: false,
				resumeLoading: false,
				finishLoading: false,
				USER_ID: September.userId,
				USER_Name: September.nickname,
				user: '',
				//				classUsers:[],
				//				allExpList:[],
				curExpId: '',
				//环境列表
				environList: [], //环境列表数据
				environTime: {}, //环境列表定时器
				///index:0,
				//虚拟机列表
				vmsList: [],
				vmsModal: false, //虚拟机列表modal
				vmStatusTimeout: {}, //虚拟机状态定时器
				timeout: {}, //虚拟机资源监控定时器
				//当前课件数据
				exp: '',
				curExp: {},
				curExpId: '',
				// 计算index
				environCol: [{
					type: 'selection',
					width: 60,
					align: 'center'
				}, {
					title: '序号',
					align: 'center',
					width: 65,
					render: (h, params) => {
						let index = (this.environPage - 1) * this.environPageSize + params.row._index + 1
						return h('span', index)
					}
				}, {
					title: '昵称',
					key: 'userName',
					align: 'center'
				}, {
					title: '类型',
					key: 'type',
					tooltip: true,
					align: 'center',
					render: (h, params) => {
						return h('span', params.row.type == 'T' ? '教师' : '学生')
					}
				}, {
					title: '课件名',
					key: 'expName',
					align: 'center',
					tooltip: true,
					render: (h, params) => {
						if(params.row.projectId) {
							return h('Tooltip', {
								props: {
									transfer: true,
									content: '点击进入拓扑图'
								}
							}, [
								h('a', {
									on: {
										'click': () => {
											this.gotoTopo(params.row);
										}
									}
								}, params.row.expName)
							])
						} else {
							return h('span', params.row.expName)
						}
					},
				}, {
					title: '部署状态',
					key: 'deployStatus',
					align: 'center',
					render: (h, params) => {
						return h('div', [
							h('Tag', {
								props: {
									color: this.$options.filters.statusFilter(params.row.deployStatus, 'color')
								}
							}, this.$options.filters.statusFilter(params.row.deployStatus, 'text')),
							h('Poptip', {
								props: {
									trigger: "hover",
									width: "300",
									content: params.row.errorMessage,
									wordWrap: true,
									transfer: true
								},
								style: {
									display: params.row.errorMessage ? '' : 'none'
								}
							}, [
								h('Icon', {
									props: {
										type: 'ios-help-circle',
										color: 'rgb(203, 2, 54)',
										size: 16
									},
									style: {
										cursor: 'pointer'
									}
								})
							])
						])
					},
					tooltip: true
				}, {
					title: '是否在线',
					render: (h, params) => {
						return h('Tag', {
							props: {
								type: 'border',
								color: params.row.online ? 'success' : ''
							}
						}, params.row.online ? '在线' : '离线')
					},
					align: 'center',
					tooltip: true
				}, {
					title: '是否接入',
					render: (h, params) => {
						let recordCol = [{
								title: '虚拟机名称',
								key: 'name',
								ellipsis: true,
								tooltip: true
							}, {
								title: '昵称',
								key: 'userName',
								tooltip: true
							},
							//                  			{
							//                  				title:'实例名称',
							//                  				key:'instanceName',
							//                  				tooltip:true
							//                  			},
							{
								title: '接入方式',
								key: 'protocol',
								tooltip: true
							}, {
								title: '登录时间',
								key: 'connectTime',
								width: 160,
								tooltip: true
							}
						];
						//讲课
						if(this.classInfo.type == '2' || (this.classInfo.type == '3' && this.classInfo.status == '1')) {
							if(params.row.type === 'T') {
								if(params.row.login) {
									return h('a', '已接入虚拟机');
								} else {
									return h('span', '未接入虚拟机');
								}
							} else {
								if(params.row.screen) {
									return h('a', '已接入投屏');
								} else {
									return h('span', '未接入投屏');
								}
							}
						} else { //实操
							let ele;
							if(params.row.login) {
								ele = h('a', '已接入虚拟机');
							} else {
								ele = h('span', '未接入虚拟机');
							}
							return h('Poptip', {
								props: {
									width: 600,
									trigger: 'hover',
									transfer: true
								},
								on: {
									//		                    				'on-popper-show':() => {
									//		                    					this.getAccessRecord(params.row)
									//		                    				}
								}
							}, [
								ele,
								h('div', {
									slot: 'content'
								}, [
									h('Table', {
										props: {
											data: params.row.accessRecords || [],
											columns: recordCol,
											height: 300
										}
									})
								])
							])
						}
					},
					align: 'center'
				}, {
					title: '操作',
					width: 270,
					render: (h, params) => {
						return h('div', [
							h('Button', {
								props: {
									type: 'info',
									size: 'small',
									disabled: this.disDeploy(params.row) || this.step != 0
								},
								style: {
									marginRight: '6px'
								},
								on: {
									click: () => {
										this.deployClass(params.row);
									}
								}
							}, '部署'),
							h('Poptip', {
								props: {
									confirm: true,
									'ok-text': "确定",
									'cancel-text': "取消",
									type: 'error',
									size: 'large',
									title: '你确定要销毁吗?',
									transfer:true
								},
								on: {
									'on-ok': () => {
										this.doExperimentDestroy(params.row);
									}
								}
							}, [
								h('Button', {
									props: {
										type: 'error',
										size: 'small',
										disabled: (!this.disbledAllBtn && (params.row.deployStatus == 3 && !params.row.disDestory)) && this.step != 0 ? false : true
									},
									style: {
										marginRight: '6px',
									},
									on: {
										click: () => {
										}
									}
								}, '销毁'),
							]),
							h('Poptip', {
								props: {
									confirm: true,
									'ok-text': "确定",
									'cancel-text': "取消",
									type: 'error',
									size: 'large',
									title: '你确定要重置吗?',
									transfer:true
								},
								style: {
									display: this.cloudType === 'h3c' ? 'none' : ''
								},
								on: {
									'on-ok': () => {
										this.doExperimentRestart(params.row);
									}
								}
							}, [
								h('Button', {
									props: {
										type: 'error',
										size: 'small',
										disabled: (!this.disbledAllBtn && (params.row.deployStatus == 3 && !params.row.disDestory)) && this.step != 0 ? false : true
									},
									style: {
										marginRight: '6px',
									},
									on: {
										click: () => {
										}
									}
								}, '重置'),
							]),
							h('Button', {
								props: {
									type: 'info',
									size: 'small',
									disabled: ((params.row.deployStatus == 3 && params.row.type == 'T') || (params.row.login)) && (this.step == 1 || (this.step == 0 && params.row.type == 'T')) ? false : true
								},
								style: {
									marginRight: '6px'
								},
								on: {
									click: () => {
										if(params.row.type == 'S' && params.row.login && (this.classInfo.type == '1' || (this.classInfo.type == '3' && this.classInfo.status == '0'))) {
											const {
												href
											} = this.$router.resolve({
												path: '/testScreen',
												query: {
													prjId: params.row.projectId,
													ecId: params.row.expId,
													userId: params.row.userId,
													classId: this.classInfo.id
												}
											});
											window.openTrain(href, '_blank')
										} else {
											this.vmsModal = true;
											this.curExpId = params.row.expId;
											this.curProjectId = params.row.projectId;
											this.getVms(params.row.projectId)
										}
									}
								}
							}, (params.row.type == 'S' && (this.classInfo.type == '1' || (this.classInfo.type == '3' && this.classInfo.status == '0'))) ? '查看实时屏幕' : '进入环境'), //学生、实操模式、教学模式的实操状态查看实时屏幕
						])
					}
				}],
				vmsCol: [{
						type: 'index',
						width: 60,
						align: 'center'
					}, {
						title: '虚拟机名称',
						key: 'name',
						align: 'center',
					},
					//        {
					//          title:this.$t('VmType'),
					//          key:'vmType',
					//          align:'center',
					//        },
					{
						title: '类型',
						key: 'vzType',
						align: 'center',
					},
					//			        {
					//			          title:this.$t('projectName'),
					//			          key:'projectName',
					//			          align:'center',
					//			        },
					// {
					//   title:'实例名称',
					//   key:'instance',
					//   align:'center',
					// },
					{
						title: '状态',
						key: 'status',
						align: 'center',
					},
					//			        {
					//			          title:this.$t('HostIp'),
					//			          key:'hostIp',
					//			          align:'center',
					//			        },
					{
						title: '主机名称',
						key: 'host',
						align: 'center',
					}, {
						title: '系统类型',
						key: 'sysType',
						align: 'center',
					},
					//			        {
					//			          title:this.$t('OSId'),
					//			          key:'osId',
					//			          align:'center',
					//			        },
					{
						title: 'CPU总量',
						key: 'cpu',
						align: 'center',
					}, {
						title: "磁盘总量(GB)",
						key: 'disk',
						align: 'center',
					}, {
						title: "内存总量(MB)",
						key: 'ram',
						align: 'center',
					}, {
						title: "CPU使用率(%)",
						key: 'cpuVal',
						align: 'center',
						render: (h, params) => {
							return h('Tag', {
								props: {
									color: 'primary'
								}
							}, params.row.cpuVal || '-')
						}
					}, {
						title: "磁盘使用率(%)",
						key: 'diskVal',
						align: 'center',
						render: (h, params) => {
							return h('Tag', {
								props: {
									color: 'primary'
								}
							}, params.row.diskVal || '-')
						}
					}, {
						title: "内存使用率(%)",
						key: 'memVal',
						align: 'center',
						render: (h, params) => {
							return h('Tag', {
								props: {
									color: 'primary'
								}
							}, params.row.memVal || '-')
						}
					}, {
						title: '用户名',
						key: 'username',
						align: 'center',
					}, {
						title: '密码',
						key: 'password',
						align: 'center',
					}, {
						title: '更新时间',
						key: 'updated',
						align: 'center',
					}, {
						title: '操作',
						key: 'action',
						align: 'center',
						width: 300,
						render: (h, params) => {
							let action = '';
							let text = '';
							let type = '';
							let disabled = false;
							if(!params.row.status) {
								return;
							}
							if(params.row.status == 'ACTIVE' || params.row.status == 'running') {
								action = "os-stop";
								text = "关机";
								type = "primary"
							} else if(params.row.status == 'DOWN' || params.row.status == 'Stopped' || params.row.status == 'SHUTOFF') {
								action = "start";
								text = "开机";
								type = "primary"
							} else {
								text = "开机";
								type = "primary";
								disabled = true;
							}
							return h('div', [
								h('div', {
									attrs: {
										id: 'selectBtn'
									},
								}, [
									h('Button', {
										props: {
											type: type,
											disabled: disabled
												//									size: 'small'
										},
										style: {
											borderRadius: '4px 0 0 4px'
										},
										on: {
											click: () => {
												this.opVm(params.row.id, action);
											}
										}
									}, text),
									h('Select', {
										props: {
											'placeholder': '',
											transfer: true
										},
										style: {
											width: '20px'
										},
										on: {
											'on-select': (val) => {
												if(val == 'reboot-hard') {
													this.rebootVm(params.row.id, 'hard_restart');
												} else if(val == 'reboot-soft') {
													this.rebootVm(params.row.id, 'soft_restart');
												} else if(val == 'rebuild') {
													this.rebuildVm(params.row.id);
												}
											}
										}
									}, [
										h('Option', {
											props: {
												value: 'reboot-soft'
											}
										}, '软重启'),
										h('Option', {
											props: {
												value: 'reboot-hard'
											}
										}, '硬重启'),
										h('Option', {
											props: {
												value: 'rebuild'
											}
										}, '重置')
									]),
								]),
								h(vmsType, {
									props: {
										row: params.row,
										ecid: this.curExpId,
										classId: this.classInfo.id
									},
									style: {
										display: 'inline-block'
									}
								})
							])
						}
					},
				],
				vmsRow(val) {
					let data = [];
					for(let i = 0; i < val.length; i++) {
						data.push({
							name: val[i]['name'],
							vmType: val[i]['vmType'],
							vzType: val[i]['vzType'],
							projectId: val[i]['projectId'],
							projectName: val[i]['projectName'],
							osId: val[i]['osId'],
							hostIp: val[i]['hostIp'],
							host: val[i]['host'],
							sysType: val[i]['sysType'],
							instance: val[i]['instanceName'],
							status: val[i]['status'],
							updated: val[i]['updated'],
							cpu: val[i]['cpu'],
							disk: val[i]['disk'],
							ram: val[i]['ram'],
							diskVal: val[i]['diskVal'],
							memVal: val[i]['memVal'],
							cpuVal: val[i]['cpuVal'],
							id: val[i]['id'],
							accesses: val[i]['accesses'],
							username: val[i]['accesses'][0].username,
							password: val[i]['accesses'][0].password
						})
					}
					return data
				},
				environPage: 1,
				environPageSize:10,
				environTotal:0,
				//批量部署，批量销毁控制
				batchDestroyLoading: false,
				batchDeployLoading: false,
				//选择的操作用户
				selectOpUsers: [],
				interval: '',
				courseStatus: 1,
			}
		},
		computed: {
			...mapState(['cloudType']),
			'disabledBatchDeploy': function() {
				return this.selectOpUsers.length == 0 //this.environList.every(environ => environ.deployStatus == 3) || this.classInfo.type == '2';
			},
			'disabledBatchDestroy': function() {
				return this.selectOpUsers.length == 0 //this.environList.every(environ => environ.deployStatus == 10) || this.classInfo.type == '2';
			},
		},
		watch: {
			classNumberId: {
				deep: true,
				handler: function(val) {
					if (val) {
						this.getClassNumberDetail()
					}
				}
			},
			countDownClassNumberId: {
				deep: true,
				handler: function(val) {
					if (val) {
						// 倒计时可能存在几秒的误差，可能提前也可能延后，连续6秒持续调用算了
						this.timer = setInterval(() => {
							this.getClassNumberDetail()
						}, 1000)
						setTimeout(() => {
							clearInterval(this.timer)
						}, 6000)
					}
				}
			},
			classInfo: {
				deep: true,
				handler: function(val, oldVal) {
					if(val.status && oldVal.status && val.status !== oldVal.status && this.classNumberInfo.classNumberId){
						this.getEnvironData();
					}
				}
			},
			classNumberInfo: {
				deep: true,
				handler: function(val, oldVal) {
					if(val.classNumberId && oldVal.classNumberId && val.classNumberId != oldVal.classNumberId && this.classInfo.status) {
						this.exp = JSON.stringify(val.expList[0]);
						this.getEnvironData();
					}
				}
			},
		},
		filters: {
			typeFilter(val) {
				let str = '';
				switch(val) {
					case '1':
						str = '实操模式';
						break;
					case '2':
						str = '讲课模式';
						break;
					case '2':
						str = '教学模式';
						break;
				}
				return str;
			},
			//0-新建 3-部署成功 6-部署失败 8-删除失败9-部署中,10没有部署
			statusFilter(val, type) {
				let str = '';
				let color = '';
				switch(val) {
					case 0:
						str = '未部署';
						color = '#888';
						break;
					case 3:
						str = '部署成功';
						color = '#06b649';
						break;
					case 6:
						str = '部署失败';
						color = '#ff4242';
						break;
					case 8:
						str = '删除失败';
						color = '#fa9901';
						break;
					case 9:
						str = '部署中';
						color = '#06b649';
						break;
					case 10:
						str = '未部署';
						color = '#888';
						break;
					case 14:
						str = '清空部署失败';
						color = '#ff8244';
						break;
					default:
						str = '未部署';
						color = '#888';
				}
				if(type == 'text') {
					return str;
				} else {
					return color;
				}
			},
		},
		created(){
			if (!navigator.getDisplayMedia && !navigator.mediaDevices.getDisplayMedia) {
				const error = 'Your browser does NOT support the getDisplayMedia API.'
			throw new Error(error)
			}
			this.upLoadUrl = `${this.baseURL}/minio/upload/permanent`;
			this.getDictscreenRecording() 
		},
		mounted() {
			console.log(this.classNumberInfo,'this.classNumberInfothis.classNumberInfo');
			//  this.video = document.querySelector('video')
			if(this.classNumberInfo.classNumberId && this.classNumberInfo.expList.length > 0 && this.classInfo.id) {
				this.exp = JSON.stringify(this.classNumberInfo.expList[0]);
				this.getEnvironData();
				this.interval = setInterval(() => {
					this.getEnvironData();
				},10000)
			}
			if (this.classNumberId) {
				this.getClassNumberDetail()
			}
			if (this.cloudType === 'h3c') {
				let index = this.vmsCol.findIndex(item => item.key === 'action')
				if (index !== -1) {
					this.vmsCol.splice(index, 1, {
						title: '操作',
						key: 'action',
						align: 'center',
						width: 300,
						render: (h, params) => {
							let action = '';
							let text = '';
							let type = '';
							let disabled = false;
							if(!params.row.status) {
								return;
							}
							if(params.row.status == 'ACTIVE' || params.row.status == 'running') {
								action = "os-stop";
								text = "关机";
								type = "primary"
							} else if(params.row.status == 'DOWN' || params.row.status == 'Stopped' || params.row.status == 'SHUTOFF') {
								action = "start";
								text = "开机";
								type = "primary"
							} else {
								text = "开机";
								type = "primary";
								disabled = true;
							}
							return h('div', [
								h('div', {
									attrs: {
										id: 'selectBtn'
									},
								}, [
									h('Button', {
										props: {
											type: type,
											disabled: disabled
												//									size: 'small'
										},
										style: {
											borderRadius: '4px 0 0 4px'
										},
										on: {
											click: () => {
												this.opVm(params.row.id, action);
											}
										}
									}, text),
									h('Select', {
										props: {
											'placeholder': '',
											transfer: true
										},
										style: {
											width: '20px'
										},
										on: {
											'on-select': (val) => {
												if(val == 'reboot-hard') {
													this.rebootVm(params.row.id, 'hard_restart');
												} else if(val == 'reboot-soft') {
													this.rebootVm(params.row.id, 'soft_restart');
												} else if(val == 'rebuild') {
													this.rebuildVm(params.row.id);
												}
											}
										}
									}, [
										h('Option', {
											props: {
												value: 'reboot-soft'
											}
										}, '软重启'),
										h('Option', {
											props: {
												value: 'reboot-hard'
											}
										}, '硬重启')
									]),
								]),
								h(vmsType, {
									props: {
										row: params.row,
										ecid: this.curExpId,
										classId: this.classInfo.id
									},
									style: {
										display: 'inline-block'
									}
								})
							])
						}
					})
				}
			}
		},
		beforeDestroy() {
			clearInterval(this.interval);
			clearInterval(this.timer)
		},
		methods: {
			getDictscreenRecording(){
				let params={
                        name:'screenRecording'
                    }
				getDictInfoByName(params).then(res=>{
					console.log(res);
					if(res.code==1){
						this.screenRecording=res.attribute.data.value
					}
					else{
						this.screenRecording=0
						this.$Message.warning('查询屏幕录制配置失败')
					};
				})
			},

			invokeGetDisplayMedia(success, error) {
                let displaymediastreamconstraints = {
                    video: {
                        displaySurface: 'monitor', // monitor, window, application, browser
                        logicalSurface: true,
                        cursor: 'always' // never, always, motion
                    }
                };
                // above constraints are NOT supported YET
                // that's why overridnig them
                displaymediastreamconstraints = {
                    video: true
                };
                if (navigator.mediaDevices.getDisplayMedia) {
                    navigator.mediaDevices.getDisplayMedia(displaymediastreamconstraints).then(success).catch(error);
                }
                else {
                    navigator.getDisplayMedia(displaymediastreamconstraints).then(success).catch(error);
                }
            },
            captureScreen(callback) {
                this.invokeGetDisplayMedia((screen) => {
                    this.addStreamStopListener(screen, () => {
                       //
                    });
                    callback(screen);
                }, function (error) {
                    console.error(error);
                    alert('已取消视频录制\n' + error);
                });
            },
            addStreamStopListener(stream, callback) {
                stream.addEventListener('ended', function () {
                    callback();
                    callback = function () { };
                }, false);
                stream.addEventListener('inactive', function () {
                    callback();
                    callback = function () { };
                }, false);
                stream.getTracks().forEach((track)=> {
                    track.addEventListener('ended', () =>{
                        this.stopRecording()
                        callback();
                        callback = function () { };
                    }, false);
                    track.addEventListener('inactive', function () {
                        callback();
                        callback = function () { };
                    }, false);
                });
            },
            startRecording() {
                this.captureScreen(screen=>{
                    // this.video.srcObject = screen;
                    this.recorder = RecordRTC(screen, {
                        type: 'video'
                    });
                    this.recorder.startRecording();
                    // release screen on stopRecording
                    this.recorder.screen = screen;
                    this.videoStart = true;
                });
            },
            stopRecordingCallback() {
                // this.video.src = this.video.srcObject = null;
                // this.video.src = URL.createObjectURL(this.recorder.getBlob());
                // 如果需要下载录屏文件可加上下面代码
                let url=URL.createObjectURL(this.recorder.getBlob())
                const a = document.createElement("a");
                document.body.appendChild(a);
                a.style.display = "none";
                a.href = url;
                a.download = this.classNumberInfo.expList[0].expName+new Date().getTime() + ".mp4";
                a.click();
                window.URL.revokeObjectURL(url);
				//上传视频
				let that = this;
				let file = new File(
					[this.recorder.getBlob()],
					this.classNumberInfo.expList[0].expName + new Date().getTime() + ".mp4",
					{
						type: "video/mp4",
					}
				);
				console.log('file', file)
				let formData = new window.FormData()
				formData.append('file',file);
				this.axios({
                            method:'post',
                            url:`${that.upLoadUrl}?visibility=company&bucket=videos&type=videos`,
                            data:formData,
                            headers:{
                                'Content-type':'multipart/form-data',
                            },
							timeout:0,
							onUploadProgress: progressEvent => {
                            	// this.$Message.info('正在上传录屏')
                            }
                        }).then(res=>{
							if(res.data.code==1){
								// this.$Message.success('上传录屏成功')
								this.recorderForm=res.data.info
								this.videoPath=res.data.data
								console.log(this.recorderForm,1111111111111111);
								this.addRecord()
							} else{
								this.$Message.warning(res.data.message)
							}
						}).catch(err=>{
                                console.log(err)
                        })
				this.recorder.screen.stop();
                this.recorder.destroy();
                this.recorder = null;
                this.videoStart = false;
            },
			addRecord(){
				let data={
					fileId:this.recorderForm.id,
					fileSize:this.recorderForm.size,
					fileName:this.recorderForm.originalName,
					filePath:this.videoPath,
					classNumberId:this.classNumberInfo.classNumberId,
					ecId:this.classNumberInfo.expList[0].expid
				}
				addRecord(data).then(res=>{
					if(res.code==1){
						this.$Message.success('上传录屏至教学班成功')
					} else{
						this.$Message.success(res.message)
					}
				}).catch(err=>{
						console.log(err)
				})
			},
            stopRecording() {
                this.recorder.stopRecording(this.stopRecordingCallback);
            },
			pauseClassNumber() {
				this.pauseLoading = true
				pauseClassNumber(this.classNumberId).then(({ code, message }) => {
					if (code !== 1) {
						this.$Message.warning(message)
						return
					}
					this.getClassNumberDetail()
					this.$emit('change-state', true)
					this.$Message.success('暂停课节成功')
				}).catch(() => {
					this.$Message.error('暂停课节异常')
				}).finally(() => {
					this.pauseLoading = false
				})
			},
			finishClassNumber() {
				this.finishLoading = true
				finishClassNumber(this.classNumberId).then(({ code, message }) => {
					if (code !== 1) {
						this.$Message.warning(message)
						return
					}
					this.getClassNumberDetail()
					this.$emit('change-state', false)
					this.$Message.success('结束课节成功')
				}).catch(() => {
					this.$Message.error('结束课节异常')
				}).finally(() => {
					this.finishLoading = false
				})
			},
			resumeClassNumber() {
				this.resumeLoading = true
				resumeClassNumber(this.classNumberId).then(({ code, message }) => {
					if (code !== 1) {
						this.$Message.warning(message)
						return
					}
					this.getClassNumberDetail()
					this.$emit('change-state', false)
					this.$Message.success('恢复课节成功')
				}).catch(() => {
					this.$Message.error('恢复课节异常')
				}).finally(() => {
					this.resumeLoading = false
				})
			},
			getClassNumberDetail() {
				getClassNumberDetail(this.classNumberId).then(({ code, message, data = {} }) => {
					if (code !== 1) {
						this.$Message.warning(message)
						return
					}
					this.courseStatus = data.state
				}).catch(() => {
					this.$Message.error('获取课节详情异常')
				})
			},
			getEnvironData() {
				this.curExp = JSON.parse(this.exp);
				let classId = this.classInfo.id;
				let params = {
					classNumberId: this.classNumberInfo.classNumberId,
					ecId: this.curExp.expid,
					nickname: this.user,
					pageIndex: this.environPage,
					pageSize:this.environPageSize
				}
				queryClassNumberList(this.classInfo.id, params).then(({
					code,
					data,
					message
				}) => {
					if(code == 1) {
						this.environList = data.items.map(environ => {
							environ.expId = this.curExp.expid;
							environ.expName = this.curExp.expName;
							environ.type = environ.type == 'experimenter' ? 'S' : 'T';
							environ.onlineText = environ.online ? '已登录' : '未登录';
							environ.classId = this.classInfo.id;
							return environ;
						})
						let userIds = this.selectOpUsers.map(user => user.userId);
						this.environList.forEach(environ => {
							if(userIds.includes(environ.userId)) {
								environ._checked = true;
							} else {
								environ._checked = false;
							}
							environ._disabled = this.disSelect(environ);
						});
						this.environTotal = data.total;
					} else {
						this.$Message.error(message)
					}
				}).catch(error => {
					this.$Message.error('获取环境信息列表失败')
				})
			},
			deployClass(environInfo) {
				this.$set(environInfo, 'disDeploy', true)
				let params = {
					userid: [environInfo.userId],
					ecid: [environInfo.expId]
				}
				deployClass(this.classInfo.id, this.classInfo.type, this.classNumberInfo.classNumberId, params).then(data => {
					if(data.code == 1) {
						this.$Message.info('操作成功')
						this.$set(environInfo, 'disDeploy', false)
						this.getEnvironData();
					} else {
						this.$set(environInfo, 'disDeploy', false)
						this.$Message.warning(data.message)
					}
				}).catch(error => {
					this.$set(environInfo, 'disDeploy', false)
				})
			},
			batchDeployClass() {
				this.batchDeployLoading = true;
				const msg = this.$Message.loading({
					content: '请求中...',
					duration: 0
				});
				let expId = this.curExp.expid;
				let params = {
					userid: this.selectOpUsers.map(env => env.userId), //filter(env => env.deployStatus == 6 || env.deployStatus == 10 || !env.deployStatus)
					ecid: [expId]
				}
				deployClass(this.classInfo.id, this.classInfo.type, this.classNumberInfo.classNumberId, params).then(data => {
					if(data.code == 1) {
						setTimeout(msg, 20);
						setTimeout(() => {
							this.$Message.success('操作成功');
						}, 20)
						this.batchDeployLoading = false;
						this.selectOpUsers = [];
						this.getEnvironData();
					} else {
						setTimeout(msg, 20);
						setTimeout(() => {
							this.$Message.error(data.message);
						}, 20)
						this.batchDeployLoading = false;
					}
				}).catch(error => {
					setTimeout(msg, 20);
					setTimeout(() => {
						this.$Message.error('请求失败');
					}, 20)
					this.batchDeployLoading = false;
				})
			},
			enterEnviron(projectId) {
				let routeData = this.$router.resolve({
					path: `/environment/${projectId}/${this.curExpId}`
				});
				window.openTrain(routeData.href, '_blank');
			},
			doExperimentDestroy(exp) {
				this.$set(exp, 'disDestory', true)
				let paramas = {
					projectId: exp.projectId,
					userId: exp.userId
				};
				experimentDestroy(paramas).then(data => {
					if(data.code == 1) {
						this.$Message.success('操作成功');
						this.$set(exp, 'disDestory', false)
						this.getEnvironData();
					} else {
						_this.$Message.error(data.message)
					}
				}).catch(error => {
					this.$Message.error(error)
				})
			},
			// 批量重置环境
			batchExperimentRestart() {
				this.batchDestroyLoading = true;
				const msg = this.$Message.loading({
					content: '请求中...',
					duration: 0
				});
				let promises = this.selectOpUsers.filter(environ => environ.projectId).map(environ => {
					return batchOpVm(environ.projectId, 'rebuild')
				})
				Promise.all(promises).then(res => {
					if (res.some(item => item.code != 1)) { // 有请求未成功
						setTimeout(msg, 20);
						setTimeout(() => {
							this.$Message.warning('重置失败');
						}, 20)
						this.batchDestroyLoading = false;
					} else {
						setTimeout(msg, 20);
						setTimeout(() => {
							this.$Message.success('重置成功');
						}, 20)
						this.selectOpUsers = [];
						this.getEnvironData();
						this.batchDestroyLoading = false;
					}
				}).catch(() => {
					setTimeout(msg, 20);
					setTimeout(() => {
						this.$Message.error('批量重置异常');
					}, 20)
					this.batchDestroyLoading = false;
				})
			},
			// 单个重置环境
			doExperimentRestart(item) {
				batchOpVm(item.projectId, 'rebuild').then(data => {
					if(data.code == 1){
						this.$Message.info('重置成功');
						this.getEnvironData();
					}else{
						this.$Message.warning(data.message);
					}
				}).catch(error => {
					this.$Message.error('环境重置异常');
				})
			},
			batchExperimentDestroy() {
				this.batchDestroyLoading = true;
				const msg = this.$Message.loading({
					content: '请求中...',
					duration: 0
				});
				let params = this.selectOpUsers.filter(environ => environ.projectId).map(environ => {
					return {
						projectId: environ.projectId,
						userId: environ.userId
					}
				})
				batchExperimentDestroy(params).then(data => {
					if(data.code == 1) {
						setTimeout(msg, 20);
						setTimeout(() => {
							this.$Message.success('操作成功');
						}, 20)
						this.selectOpUsers = [];
						this.getEnvironData();
						this.batchDestroyLoading = false;
					} else {
						setTimeout(msg, 20);
						setTimeout(() => {
							this.$Message.error(data.message);
						}, 20)
						this.batchDestroyLoading = false;
					}
				}).catch(error => {
					setTimeout(msg, 20);
					setTimeout(() => {
						this.$Message.error('请求失败');
					}, 20)
					this.batchDestroyLoading = false;
				})
			},
			getVms(projectId) {
				getVms(projectId).then(data => {
					if(data.code == 1) {
						this.vmsList = data.attribute.vms;
						this.getCPUData();
						this.getVmStatus(data.attribute.vms.map(device => device.id));
					} else {
						this.vmsList = [];
					}
				})
			},
			getVmStatus(vms) {
				clearTimeout(this.vmStatusTimeout);
				if(vms.length <= 0) {
					return;
				}
				queryVmStatus(vms).then(res => {
						if(res.code == 1 && res.list) {
							this.vmsList.forEach(host => {
								res.list.forEach(vm => {
									if(host.id == vm.vmId) {
										this.$set(host, 'status', vm.status);
										return;
									}
								})
							})
							if(this.vmsModal) {
								this.vmStatusTimeout = setTimeout(() => {
									this.getVmStatus(vms);
								}, 3000)
							}
						}
					})
					.catch(error => {
						// Alert("danger",error);
					})
			},
			cancelTimeout() {
				clearTimeout(this.vmStatusTimeout);
			},
			updateClassStatus(status) {
				updateClassStatus(this.curClass.id, status).then(data => {
					if(data.code == 1) {
						this.$Message.info('操作成功')
					} else {
						this.$Message.warning(data.message)
					}
				})
			},
			rowClassName(row, index) {
				if(row.type === "T") {
					return 'demo-table-info-row';
				}
				return '';
			},
			changeEnvironPage(page) {
				this.environPage = page;
				this.getEnvironData();
			},
			disDeploy(environ) {
				let status1 = (this.classInfo.type == '2' && environ.type == 'S') || (this.classInfo.type == '1' && environ.type == 'T'); //讲课模式的学生,不需要部署
				//6：部署失败  10：未部署   / 部署状态为undefined /部署状态为0，但是有错误信息
				if(!this.disbledAllBtn && !environ.disDeploy && !status1 && this.courseStatus != 3 && ((environ.deployStatus == 6) || (environ.deployStatus == 10) || (!environ.deployStatus) || (environ.deployStatus === 0 && environ.errorMessage))) {
					return false
				} else {
					return true
				}
				//((params.row.deployStatus == 6 && !status1) || (params.row.deployStatus == 10 && !status1) || (!params.row.deployStatus && params.row.deployStatus != 0 && !status1)) ? false : true
			},
			//操作虚拟机
			opVm(id, action) {
				opVms(id, action).then(data => {
					if(data.code == 1) {
						this.$Message.info('操作成功')
						this.getVms(this.curProjectId);
					} else {
						this.$Message.error(data.message)
					}
				}).catch(error => {
					this.$Message.error('操作失败')
				})
			},
			//重置虚拟机
			rebuildVm(id) {
				rebuildVm(id).then(data => {
					if(data.code == 1) {
						this.$Message.info('操作成功');
						this.getVms(this.curProjectId);
					} else {
						this.$Message.error(data.message)
					}
				}).catch(error => {
					this.$Message.error('操作失败')
				})
			},
			//重启虚拟机
			rebootVm(id, type) {
				rebootVm(id, type).then(data => {
					if(data.code == 1) {
						this.$Message.info('操作成功')
						this.getVms(this.curProjectId);
					} else {
						this.$Message.error(data.message)
					}
				}).catch(error => {
					this.$Message.error('操作失败')
				})
			},
			clearTimeout() {
				clearTimeout(this.timeout);
			},
			getCPUData(host) {
				this.clearTimeout();
				let index = 0;
				this.vmsList.forEach(host => {
					if(!host.instanceName) {
						return;
					}
					getmemdata({
							vmId: host.id
						})
						.then(data => {
							if(data.code == 1) {
								index++;
								let response = data.data;
								if(response.cpuUsage) {
									this.$set(host, 'cpuRate', response.cpuUsage + '%');
									this.$set(host, 'cpuVal', response.cpuUsage);
								} else {
									this.$set(host, 'cpuRate', '0%');
									this.$set(host, 'cpuVal', 0);
								}
								if(response.diskUsage) {
									this.$set(host, 'diskRate', response.diskUsage + '%');
									this.$set(host, 'diskVal', response.diskUsage);
								} else {
									this.$set(host, 'diskRate', '0%');
									this.$set(host, 'diskVal', 0);
								}
								if(response.memoryUsage) {
									this.$set(host, 'memRate', response.memoryUsage + '%');
									this.$set(host, 'memVal', response.memoryUsage);
								} else {
									this.$set(host, 'memRate', '0%');
									this.$set(host, 'memVal', 0);
								}
								//                          if(response.netIncomingBytes){
								//                              this.$set(host,'traffic',(response.netIncomingBytes +"/" +response.netOutgoingBytes));
								//                          }else{
								//                              this.$set(host,'traffic',"0.00/0.00");
								//                          }
								if(index == this.vmsList.length && this.timeout && this.vmsModal) {
									this.timeout = setTimeout(() => {
										this.getCPUData(host);
									}, 5000)
								}
							} else {
								//this.$Message.error('查询失败')
							}
						})
						.catch(error => {
							// Alert('danger',error.statusText)
						})
				})
			},
			gotoTopo(scene) {
				if(scene.projectId && scene.deployStatus != 10) {
					window.openTrain(`/jjzzTopo/index.html#/ProjectViews?projectId=${scene.projectId}`);
				} else {
					this.$Message.warning('工程不存在！');
				}
			},
			// 选择题目并添加
			addDeployUser(selection, row) {
				if(!row) { // 全选
					selection.forEach(user => {
						let selQuesIds = this.selectOpUsers.map(user => user.userId);
						if(!selQuesIds.includes(user.userId)) { // 添加不包含的题目
							let environ = this.environList.find(environ => environ.userId == user.userId);
							if(environ) {
								environ._checked = true;
							}
							this.selectOpUsers.push(user)
						}
					})
				} else {
					let environ = this.environList.find(environ => environ.userId == row.userId);
					if(environ) {
						environ._checked = true;
					}
					this.selectOpUsers.push(row)
				}
			},
			// 删除选中的题目
			removeDeployUser(selection, row) {
				if(!row) { //全选
					this.environList.forEach(environ => {
						environ._checked = false;
						this.handleClose(environ.userId);
					})
				} else {
					let environ = this.environList.find(environ => environ.userId == row.userId);
					if(environ) {
						environ._checked = false;
					}
					this.handleClose(row.userId);
				}
			},
			handleClose(userId) {
				let index = this.selectOpUsers.findIndex(environ => environ.userId == userId);
				this.selectOpUsers.splice(index, 1)
			},
			disDestory(environ) {
				return !this.disbledAllBtn && (environ.deployStatus == 3 && !environ.disDestory) ? false : true;
			},
			disSelect(environ) {
				if(this.step === 0) {
					return this.disDeploy(environ);
				} else {
					return this.disDestory(environ);
				}
			}
		}
	}
</script>

<style scoped>
.ml4 {
	margin-left: 4px;
}
</style>
<style>
	.ivu-table .demo-table-info-row td {
		background-color: #fff7e6;
		/*color: #ff9900;
        font-weight: bold;*/
	}
	
	#selectBtn {
		margin-right: 5px;
		display: inline-block;
	}
	
	#selectBtn .ivu-select-selection {
		border-radius: 0 4px 4px 0;
	}
	
	#selectBtn .ivu-select-arrow {
		right: 4px;
	}
	
	#selectBtn .ivu-select-selected-value {
		display: none;
	}
</style>